package com.wang.interview.data_structures_and_algorithms.a02_queue;


import java.util.NoSuchElementException;
import java.util.Scanner;

/**
 * @author: wang
 * @date: 2021/8/3 13:45
 * @description:
 */
public class MyQueue {
    private int[] arr;
    private int head;
    private int cursor;
    private int max;

    public MyQueue(int size) {
        this.arr = new int[size];
        this.head = 0;
        this.cursor = 0;
        this.max = size - 1;
    }

    public boolean isEmpty() {
        return cursor == head;
    }

    public boolean isFull() {
        return ( cursor + 1 ) % max == head;
    }

    public void add(int num) {
        if (isFull()) {
            System.out.println("队列已满");
        } else {
            arr[cursor] = num;
            cursor = ( cursor + 1 ) % max;
        }
    }

    public int pop() {
        if (isEmpty()) {
            throw new NoSuchElementException("队列为空");
        } else {
            int temp = arr[head];
            head = ( head +1 ) % max;
            return temp;
        }
    }

    public int peek() {
        if (isEmpty()) {
            throw new NoSuchElementException("队列为空");
        } else {
            return arr[head];
        }
    }

    public void show() {
        if (isEmpty()) {
            System.out.println("队列为空");
        } else {
            while ( ( head ) % max != cursor ) {
                System.out.printf("queue[%d]=%d\n", head, arr[head++]);
            }
        }
    }

    public static void main(String[] args) {
        MyQueue queue = new MyQueue(3);
        Scanner sc = new Scanner(System.in);
        label:while ( true ) {
            System.out.println("请输入如下命令：");
            System.out.println("s 展示队列 ");
            System.out.println("a 添加 ");
            System.out.println("p 弹出队首 ");
            System.out.println("h 查看队首 ");
            System.out.println("q 退出 ");
            String next = sc.next();
            switch (next) {
                case "s" :
                    queue.show();
                    break;
                case "a" :
                    System.out.println("请输入");
                    queue.add(sc.nextInt());
                    break;
                case "p" :
                    try {
                        System.out.println(queue.pop());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case "h" :
                    try {
                        System.out.println(queue.peek());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case "q" :
                    System.out.println("程序结束");
                    break label;
                default:
                    break;
            }
        }
    }

}
